﻿using System;
using System.Collections.Specialized;
using System.Data;
using System.Reflection;
using System.Text;
using System.Web.UI;
using System.Xml;
using AMS.Inventory.Entities;
using VitCode.BaseDataPageCreator;
using VitCode.Castle.DataAccess;
using VitCode.Castle.Helper;
using VitCode.Web.UI;


namespace AMSInventoryWeb.UserControls
{
    public partial class SelectedAssetCtl : UserControl
    {
        private readonly CreateControlHelper m_CreateCtlHlp = new CreateControlHelper();
        private PageBuilder m_PageBuilder;

        public string SettingXmlPath
        {
            get { return AppDomain.CurrentDomain.BaseDirectory + "Setting\\BaseDataSet.xml"; }
        }

        public string ClassName
        {
            get { return hdnClassName.Value; }
            set { hdnClassName.Value = value; }
        }

        public string TypeName
        {
            get { return hdnTypeName.Value; }
            set { hdnTypeName.Value = value; }
        }

        public string PlanKeyVal
        {
            get { return hdnKeyVal.Value; }
            set
            {
                string val = value;
                if (val.Length == 0)
                    val = Guid.Empty.ToString();
                hdnKeyVal.Value = val;
            }
        }

        public string MenuId
        {
            get { return Request.QueryString["MenuId"]; }
        }


        private string QueryCondition
        {
            get
            {
                if (ViewState["QueryCondition"] != null)
                    return ViewState["QueryCondition"].ToString();
                else
                    return "";
            }
            set { ViewState["QueryCondition"] = value; }
        }

        private string ReturnQueryStringValue(string keyString)
        {
            string strValue = Request.QueryString[keyString];
            if (strValue == null)
                strValue = "";
            return Convert.ToString(strValue);
        }

        public void SetCtlDisabled()
        {
            btnClear.Enabled = false;
            btnDelete.Enabled = false;
        }

        protected override void OnInit(EventArgs e)
        {
            ClassName = ReturnQueryStringValue("ClassName");
            TypeName = ReturnQueryStringValue("TypeName");
            if (m_PageBuilder == null)
                m_PageBuilder = new PageBuilder(Page, SettingXmlPath);
            XmlNode listSqlNode = m_PageBuilder.GetPgListSqlNode(ClassName, TypeName, PlanInfo.SELECTED_ASSET_LIST_SQL);
            if (listSqlNode != null)
            {
                m_PageBuilder.SetPgListAttribute(pgList, listSqlNode, true,true, false);
            }
            base.OnInit(e);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            pgList.DataSourceBuilderDelegate = new PaginationGrid.GridDataSourceBuilderDelegate(BindPgList);
            if (!IsPostBack)
            {
                m_CreateCtlHlp.SetDdlCondition(pgList, ddlCondition);
            }
        }

        public void SetData()
        {
            pgList.BindGrid();
        }

        private PaginationGridDataSourceBuilder BindPgList()
        {
            string sql = m_PageBuilder.GetPgListSqlValue(ClassName, TypeName, PlanInfo.SELECTED_ASSET_LIST_SQL);
            sql = sql.Replace("\r\n", " ").Replace("\t", " ");
            if (sql.IndexOf("{0}") > -1)
                sql = sql.Replace("{0}", PlanKeyVal);
            sql += " " + QueryCondition;
            var dataBuilder = new UserDataSourceBuilder(sql, pgList);
            return dataBuilder;
        }

        protected void ConditionSelector1_SelectCondition(SelectConditionEventArgs e)
        {
            QueryCondition = null;
            if (ConditionSelector1.SelectedConditionString.Length > 0)
                QueryCondition = " where " + ConditionSelector1.SelectedConditionString;
            pgList.BindGrid();
        }

        protected void btnQuery_Click(object sender, EventArgs e)
        {
            QueryCondition = QueryHelper.GetQueryCondition(ddlCondition.SelectedValue, txtValue.Text, rbtAmount.Checked);
            pgList.BindGrid();
        }

        protected void pgList_OnGridItemSelect(object sender, PaginationGridItemSelectArgs e)
        {
            string strUrlVal = ("/BaseData/ObjEdit.aspx?IsNav=false&MenuId=" + MenuId + "&ClassName=" + typeof(InventoryInfo).Name + "&Id=" + e.SelectedDataKeyValue);
            m_PageBuilder.ShowModalDialog(strUrlVal, Page, typeof(InventoryInfo).Name, "");
        }

        protected void btnSelect_Click(object sender, EventArgs e)
        {
            string strDelVal = pgList.GetSelectedItem(1);
            if(strDelVal.Trim().Length == 0)
            {
                Alert.WebMessageBox(Page,"请选择资产!");
                return;
                
            }
            CreateControlHelper cch = new CreateControlHelper();
            Type classType = typeof(InventoryInfo);
            string proName = m_PageBuilder.GetPageKeyField(classType.Name);
            PropertyInfo pi = classType.GetProperty(proName);
            var acc = new BaseDataAccess();
            acc.BeginTransaction();
            try
            {
                StringCollection sc = acc.DeleteReErrMsg(false, strDelVal, pi.PropertyType, classType);
                if (sc.Count == 0)
                {
                    acc.Commit();
                    Alert.WebMessageBox(Page,"所选彻底删除成功");
                }
                else
                {
                    var sb = new StringBuilder();
                    sb.Append("部分数据不能删除,原因如下:\r\n");
                    for (int i = 0; i < sc.Count; i++)
                    {
                        string str = sc[i];
                        cch.SetDeleteErrMsgEachClassMemo(ref str);
                        sb.Append(str + "\r\n");
                    }
                    acc.RollBack();
                    Alert.WebMessageBox(Page,sb.ToString());
                }
                pgList.BindGrid();
            }
            catch
            {
                acc.RollBack();
                throw;
            }
            finally
            {
                acc.CloseSession();
            }
        }

        protected void btnClear_Click(object sender, EventArgs e)
        {
            var acc = new BaseDataAccess();
            acc.BeginTransaction();
            try
            {
                acc.DeleteObjectsByKeyValues(typeof (InventoryInfo).Name, "PlanId", PlanKeyVal);
                acc.Commit();
                Alert.WebMessageBox(Page,"待盘资产清除成功");
                pgList.BindGrid();
            }
            catch
            {
                acc.RollBack();
                throw;
            }
            finally
            {
                acc.CloseSession();
            }
        }
    }
}